//图像操作
var img;
var imageData;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var canvasContainer = document.getElementById("images-canvas-container");


// Add events to the file input button
var fileInput = document.getElementById("file-input");
fileInput.addEventListener("click", function () { this.value = null; }, false);
fileInput.addEventListener("change", handleImageSelection, false);

//
var Formatflag=document.getElementById("format");
var thresholdvalue = 128;

function horizontal1bit(data, canvasWidth, canvasHeight) {
	var output_string = "";
	var output_index = 0;

	var byteIndex = 7;
	var number = 0;

	// format is RGBA, so move 4 steps per pixel
	for (var index = 0; index < data.length; index += 4) {
		// Get the average of the RGB (we ignore A)
		var avg = (data[index] + data[index + 1] + data[index + 2]) / 3;
		if (avg > thresholdvalue) {
			number += Math.pow(2, byteIndex);
		}
		byteIndex--;

		// if this was the last pixel of a row or the last pixel of the
		// image, fill up the rest of our byte with zeros so it always contains 8 bits
		if ((index != 0 && (((index / 4) + 1) % (canvasWidth)) == 0) || (index == data.length - 4)) {

			byteIndex = -1;
		}

		// When we have the complete 8 bits, combine them into a hex value
		if (byteIndex < 0) {
			var byteSet = number.toString(16);
			if (byteSet.length == 1) { byteSet = "0" + byteSet; }
			output_string += byteSet + ", ";
			output_index++;
			if (output_index >= 16) {
				output_string += "\n";
				output_index = 0;
			}
			number = 0;
			byteIndex = 7;
		}
	}
	canvas.width = 212;
	canvas.height = 104;
	canvasContainer.appendChild(canvas);
	ctx.putImageData(imageData, 0, 0);
	return output_string;
}

// Handle selecting an image with the file picker
function handleImageSelection(evt) {

	var files = evt.target.files;

	for (var i = 0, f; f = files[i]; i++) {

		// Only process image files.
		if (!f.type.match("image.*")) {
			continue;
		}

		var reader = new FileReader();

		reader.onload = (function (file) {
			return function (e) {
				// Render thumbnail.
				img = new Image();

				img.onload = function () {
					canvas.height = 104;
					canvas.width = 212;
					var tempwidth = 212 / img.width;
					var tempheight = 104 / img.height;
					ctx.save();
					ctx.scale(tempwidth, tempheight);
					ctx.drawImage(img, 0, 0);
					ctx.restore();
					blackAndWhite();
					// blackAndWhite(canvas, ctx);
				};
				img.src = e.target.result;
			};
		})(f);
		reader.readAsDataURL(f);
	}
}

// Easy way to update settings controlled by a textfield
function updateInteger(fieldName) {
	thresholdvalue = document.getElementById(fieldName).value;
	blackAndWhite()
}

// function updateFormat(fieldName) {
// 	Formatflag = document.getElementById(fieldName).value;
// 	console.log(Formatflag);
// }

// Invert the colors of the canvas
function invert() {
	var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
	var data = imageData.data;
	for (var i = 0; i < data.length; i += 4) {
		data[i] = 255 - data[i];         // red
		data[i + 1] = 255 - data[i + 1];     // green
		data[i + 2] = 255 - data[i + 2];     // blue
	}
	ctx.putImageData(imageData, 0, 0);
}

// Make the canvas black and white
function blackAndWhite() {
	canvas.height = 104;
	canvas.width = 212;
	var tempwidth = 212 / img.width;
	var tempheight = 104 / img.height;
	ctx.save();
	ctx.scale(tempwidth, tempheight);
	ctx.drawImage(img, 0, 0);
	ctx.restore();
	imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
	var data = imageData.data;
	for (var i = 0; i < data.length; i += 4) {
		var avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
		avg > thresholdvalue ? avg = 255 : avg = 0;
		data[i] = avg; // red
		data[i + 1] = avg; // green
		data[i + 2] = avg; // blue
	}
	ctx.putImageData(imageData, 0, 0);
}

function imageToString(invertflag) {
	// extract raw image data

	ctx.fillRect(0, 0, canvas.width, canvas.height);

	ctx.setTransform(1, 0, 0, 1, 0, 0); // start with identity matrix transform (no rotation).
	canvas.width = 104;
	canvas.height = 212;
	canvasContainer.appendChild(canvas);

	ctx.translate(canvas.width / 2.0, canvas.height / 2.0);
	ctx.rotate(-((Math.PI) / 2));
	ctx.translate(-canvas.width / 2.0, -canvas.height / 2.0);
	var offset_x = 0;
	var offset_y = 0;
	offset_x = Math.round((canvas.width - 212) / 2);
	offset_y = Math.round((canvas.height - 104) / 2);
	ctx.drawImage(img, 0, 0, 212, 104, offset_x, offset_y, 212, 104);

	if(invertflag==1)
	{
		invert();
	}

	var imageDatatostring = ctx.getImageData(0, 0, canvas.width, canvas.height);
	var data = imageDatatostring.data;
	return horizontal1bit(data, canvas.width, canvas.height);
}

// Output the image string to the textfield
function outputString(invertflag) {
	var output_string = "";

	output_string = imageToString(invertflag);
	
	return output_string
	
}

function updatatoServer() {
	var Original_output_string = "";
	var Invert_output_string = "";
	Original_output_string=outputString(0);
	Invert_output_string=outputString(1);
	console.log(Original_output_string);
	console.log(Invert_output_string);
	
	var file = new File([Original_output_string],"data.txt");
	console.log(file);

	const formData = new FormData();

    // append 文件
    formData.append('file', file);
	console.log(formData);
	var xhr = new XMLHttpRequest();
	xhr.open("post", "/EvilEmail.html", true);
	// xhr.setRequestHeader("Content-Type", "text/plain");
	xhr.send(formData);
}
